package com.wj.facedetect.activity.home;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wj.facedetect.R;
import com.wj.facedetect.activity.base.BaseActivity;
import com.wj.facedetect.bean.home.FaceCardBean;
import com.wj.facedetect.bean.home.FaceCardVerifyBean;
import com.wj.facedetect.presenter.HomePresenter;
import com.wj.facedetect.util.CameraUtil;
import com.wj.facedetect.util.CommonUtils;
import com.wj.facedetect.util.DialogUtil;
import com.wj.facedetect.util.ToastUtil;
import com.wj.facedetect.view.IBaseView;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by tangkun on 2018/3/30.
 */

public class FaceCardActiviy extends BaseActivity implements View.OnClickListener, IBaseView {
    private static final String TAG = "FaceCardActiviy";
    private TextView tvLeft;
    private ImageView ivFace;
    private ImageView ivCard;
    private TextView tvFace;
    private TextView tvCard;
    private TextView tvCompare;
    private TextView tvVerifyResult;
    private Uri faceUri;
    private Uri cardUri;
    private Bitmap faceBitmap;
    private Bitmap cardBitmap;
    private String faceBase64;
    private String cardBase64;
    private HomePresenter homePresenter;
    private final int CODE_FACE = 0x001;
    private final int CODE_CARD = CODE_FACE + 1;
    private final int DETECT_TYPE_FACE = 0x001;
    private final int DETECT_TYPE_CARD = DETECT_TYPE_FACE + 1;
    private final int REQ_GET_HEAD = 0x110;
    private final int REQ_COMPARE = REQ_GET_HEAD + 1;
    private int detectType;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face_card);
        homePresenter = new HomePresenter(this);
        initView();
    }

    private void initView() {
        tvLeft = (TextView) findViewById(R.id.tv_left);
        ivFace = (ImageView) findViewById(R.id.iv_face_collect);
        ivCard = (ImageView) findViewById(R.id.iv_card_collect);
        tvFace = (TextView) findViewById(R.id.tv_face_collect);
        tvCard = (TextView) findViewById(R.id.tv_card_collect);
        tvCompare = (TextView) findViewById(R.id.tv_compare);
        tvVerifyResult = (TextView) findViewById(R.id.tv_verify_result);
        tvLeft.setOnClickListener(this);
        ivCard.setOnClickListener(this);
        ivFace.setOnClickListener(this);
        tvCompare.setOnClickListener(this);
        findViewById(R.id.rlyt_base).getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                ViewGroup.LayoutParams layoutParams = ivCard.getLayoutParams();
                layoutParams.height = ivCard.getMeasuredHeight();
                layoutParams.width = ivCard.getMeasuredWidth();
                ivCard.setLayoutParams(layoutParams);
                //
                layoutParams = ivFace.getLayoutParams();
                layoutParams.height = ivFace.getMeasuredHeight();
                layoutParams.width = ivFace.getMeasuredWidth();
                ivFace.setLayoutParams(layoutParams);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_left:
                finish();
                break;
            case R.id.iv_face_collect://拍摄人脸
            {
                Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                Uri photoUri = CameraUtil.buildPhotoUri(this);
                CameraUtil.grantPermission(this, takeIntent, photoUri);
                faceUri = photoUri;
                takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                startActivityForResult(takeIntent, CODE_FACE);
            }
            break;
            case R.id.iv_card_collect://拍摄证件
            {
                Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                Uri photoUri = CameraUtil.buildPhotoUri(this);
                CameraUtil.grantPermission(this, takeIntent, photoUri);
                cardUri = photoUri;
                takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                startActivityForResult(takeIntent, CODE_CARD);
            }
            break;
            case R.id.tv_compare://比对
                if (tvVerifyResult.getText().toString().isEmpty()) {//比对
                    if (faceBase64 == null || faceBase64.isEmpty()) {
                        Toast.makeText(this, "请采集人像!", Toast.LENGTH_SHORT).show();
                        return;
                    } else if (cardBase64 == null || cardBase64 == null) {
                        Toast.makeText(this, "请采集证件!", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    requestData();
                } else {//重置
                    ivFace.setImageResource(R.mipmap.renxiangcj);
                    tvFace.setVisibility(View.VISIBLE);
                    ivCard.setImageResource(R.mipmap.zhengjiancj);
                    tvCard.setVisibility(View.VISIBLE);
                    ivFace.setClickable(true);
                    ivCard.setClickable(true);
                    tvVerifyResult.setText(null);
                    tvCompare.setText("开始比对");
                    //
                    faceUri = null;
                    cardUri = null;
                    faceBase64 = null;
                    cardBase64 = null;
                    if (faceBitmap != null && !faceBitmap.isRecycled()) {
                        faceBitmap.recycle();
                    }
                    faceBitmap = null;
                    if (cardBitmap != null && !cardBitmap.isRecycled()) {
                        cardBitmap.recycle();
                    }
                }
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case CODE_FACE:
                if (resultCode == RESULT_OK) {
                    faceBitmap = CameraUtil.handlePhotoByDecodeAndRotateUri(this, 480, 800, faceUri);
                    if (faceBitmap != null) {
                        //人脸识别
                        detectType = DETECT_TYPE_FACE;
                        requestFaceDetect(faceBitmap);
                    }
                }
                break;
            case CODE_CARD:
                if (resultCode == RESULT_OK) {
                    cardBitmap = CameraUtil.handlePhotoByDecodeAndRotateUri(this, 480, 800, cardUri);
                    if (cardBitmap != null) {
                        //人脸识别
                        detectType = DETECT_TYPE_CARD;
                        requestFaceDetect(cardBitmap);
                    }
                }
                break;
        }
    }

    private void requestFaceDetect(Bitmap bitmap) {
        Map<String, String> paramsMap = new HashMap<>();
        String base64 = CommonUtils.bitmapToBase64(bitmap);
        base64 = base64.replace("\n", "");
        paramsMap.put("image_content_base64", base64);
        showProgressDialog();
        homePresenter.doRequestFaceCardDetect((new Gson()).toJson(paramsMap), REQ_GET_HEAD, this);
    }

    public void requestData() {
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("feature_base64_1", faceBase64);
        paramsMap.put("feature_base64_2", cardBase64);
        showProgressDialog();
        homePresenter.doRequestFaceCardVerify((new Gson()).toJson(paramsMap), REQ_COMPARE, this);
    }

    @Override
    protected void onDestroy() {
        if (cardBitmap != null && !cardBitmap.isRecycled()) {
            cardBitmap.recycle();
        }
        if (faceBitmap != null && !faceBitmap.isRecycled()) {
            faceBitmap.recycle();
        }
        homePresenter.getModel().cancleRequest(this);
        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onSuccess(int what, Object data, Object carryObj) {
        dismissProgressDialog();
        switch (what) {
            case REQ_GET_HEAD:
                //获取头像
                FaceCardBean faceCardBean = (FaceCardBean) data;
                if (faceCardBean != null && faceCardBean.getResults() != null && !faceCardBean.getResults().isEmpty()) {
                    FaceCardBean.ResultBean resultBean = faceCardBean.getResults().get(0);
                    if (detectType == DETECT_TYPE_FACE) {
                        faceBase64 = resultBean.getFeature_base64();
                        ivFace.setImageBitmap(faceBitmap);
                        tvFace.setVisibility(View.INVISIBLE);
                    } else if (detectType == DETECT_TYPE_CARD) {
                        cardBase64 = resultBean.getFeature_base64();
                        ivCard.setImageBitmap(cardBitmap);
                        tvCard.setVisibility(View.INVISIBLE);
                    }
                } else {//未识别出人脸
                    DialogUtil.showErrorMsg(this, "未识别出人脸,请重新采集!");
                }
                break;
            case REQ_COMPARE:
                //比较
                // TODO: 2018/9/11 待修改
                FaceCardVerifyBean faceCardVerifyBean = (FaceCardVerifyBean) data;
                double siml = faceCardVerifyBean.getSimilarity();
                if (siml != Double.MIN_VALUE) {
                    siml = new BigDecimal(siml).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    String resultStr = "相似度: " + String.valueOf(siml);
                    SpannableString ss = new SpannableString(resultStr);
                    AbsoluteSizeSpan asp = new AbsoluteSizeSpan(17, true);
                    ss.setSpan(asp, resultStr.length() - String.valueOf(siml).length(), resultStr.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                    tvVerifyResult.setText(ss);
                    ivCard.setClickable(false);
                    ivFace.setClickable(false);
                    //
                    tvCompare.setText("重置");
                } else {
                    DialogUtil.showErrorMsg(this, "比对异常!");
                }
                break;
        }
    }

    @Override
    public void onError(int what, Exception e, Object carryObj) {
        dismissProgressDialog();
        ToastUtil.showMessage("网络异常");
    }

    @Override
    public void onFail(int what, int errorCode, String errorMsg, Object carryObj) {
        dismissProgressDialog();
    }
}
